package in.muton.edushare.newentities;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.processing.objects.DeptDataHandler;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.UserDeptLinkDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.Departments;
import com.edushare.common.vo.UserDeptLink;
import com.edushare.common.vo.UserRoles;
import com.edushare.common.vo.Users;

public class DeptUserCreator extends UserInviter {
	private static final long serialVersionUID = 9171315509055429782L;
	private ORMInterface ormInterface;
	private IModel<Departments> dept;
	private Integer deptRole;

	public DeptUserCreator(ORMInterface ormInterface, IModel<Departments> dept,
			Integer deptRole) {
		super(ormInterface);
		this.dept = dept;
		this.deptRole = deptRole;
		this.ormInterface = ormInterface;
	}

	public List<String> addUsersToDept(String userList) {
		List<String> statusList = new ArrayList<String>();
		String[] users = UserInviter.breakString(userList);
		UserDeptLinkDAO udlDAO = new UserDeptLinkDAO(EduShareSession.get()
				.getSessionORMInterface());

		UnivUserCreator uuc = new UnivUserCreator(ormInterface,
				new DeptDataHandler(dept).getOwner(),
				getMatchingUnivRole(deptRole));

		for (String u : users) {
			Users userVO = getUserByString(u);
			if (userVO != null) {
				statusList.add(udlDAO.addUserFB(dept.getObject(), userVO,
						deptRole, EduShareSession.get().getLoggedInUser()));

			} else {
				if (isEmailId(u)) {
					uuc.addUsersToUniv(u);
					userVO = getUserByString(u);
					if (userVO != null) {
						statusList.add(udlDAO.addUserFB(dept.getObject(),
								userVO, deptRole, EduShareSession.get().getLoggedInUser()));
					} else {
						statusList.add("Unable to invite user "
							+ u + ". Please provide valid Edushare username or email ID");

					}
				} else {
					statusList.add("Unable to determine the type of user "
						+ u + ". Please provide valid Edushare username or email ID");
				}
			}
		}
		return statusList;
	}

	public int convertDeptRoleToUniv(int roleType) {
		switch (roleType) {
		case UserDeptLink.PRIMARY_ADMIN:
		case UserDeptLink.SECONDARY_ADMIN:
		case UserDeptLink.TEACHER:
			return UserRoles.TEACHER_ROLE;
		case UserDeptLink.STUDENT:
			return UserRoles.STUDENT_ROLE;
		}
		return -1;
	}
}
